import 'package:flutter/material.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/util/speak/speak_type_option.dart';
import 'package:flutter_deer/util/speak/tts_manger.dart';
import 'package:get/get.dart';

class SettingSpeakEditPage extends StatefulWidget {
  final int speakId;

  const SettingSpeakEditPage({super.key, required this.speakId});

  @override
  State<SettingSpeakEditPage> createState() => _SettingSpeakEditPageState();
}

class _SettingSpeakEditPageState extends State<SettingSpeakEditPage> {
  late TextEditingController _contentController;
  late TextEditingController _supplyController;
  late String _previewText;
  late List<CommonData> _btnList;
  late SpeakStyleData? _speakStyleData;
  final TtsEngineManager _tts = Get.find<TtsEngineManager>();

  @override
  void initState() {
    super.initState();
    print('SettingSpeakEditPage ${widget.speakId}');

    // 获取当前编辑的SpeakStyleData
    _speakStyleData = _tts.speakStyleList.firstWhereOrNull((element) => element.speakId == widget.speakId);

    // 初始化按钮列表
    _btnList = SpeakTypeEnu.getList(widget.speakId);

    // 初始化内容
    String content = _speakStyleData?.speakContent ?? "";
    String supply = _speakStyleData?.speakSupply ?? "交易成功";

    if (content.isEmpty) {
      // 如果没有内容，则使用默认的
      for (var item in _btnList) {
        content += "[${item.payTypeName}]";
      }
    } else {
      // 如果有内容，则更新按钮列表的选中状态
      for (var item in _btnList) {
        item.canUse = content.contains(item.payTypeName);
      }
    }

    _contentController = TextEditingController(text: content);
    _supplyController = TextEditingController(text: supply);
    _previewText = "预览：${SpeakEnu.demoFormatSpeak(content)}  $supply";
  }

  @override
  void dispose() {
    _contentController.dispose();
    _supplyController.dispose();
    super.dispose();
  }

  void _updatePreview() {
    setState(() {
      _previewText = "预览：${SpeakEnu.demoFormatSpeak(_contentController.text)}  ${_supplyController.text}";
    });
  }

  void _toggleItem(CommonData item) {
    setState(() {
      item.canUse = !item.canUse;
      if (item.canUse) {
        _contentController.text += "[${item.payTypeName}]";
      } else {
        _contentController.text = _contentController.text.replaceAll("[${item.payTypeName}]", "");
      }
      _updatePreview();
    });
  }

  void _save() {
    // 更新数据
    if (_speakStyleData != null) {
      _speakStyleData!.speakContent = _contentController.text;
      _speakStyleData!.speakSupply = _supplyController.text;
    } else {
      // 如果没有找到，则添加新的
      _tts.speakStyleList.add(SpeakStyleData(
        speakId: widget.speakId,
        speakStyle: SpeakTypeEnu.values.firstWhere((element) => element.speakId == widget.speakId).speakStyle,
        speakContent: _contentController.text,
        speakSupply: _supplyController.text,
      ));
    }

    // 保存到本地
    _tts.saveSpeakStyleList();
  }

  void _preview() {
    // TODO: 实现试听功能
    // 这里应该调用TTS引擎进行试听
    print("试听: ${SpeakEnu.demoFormatSpeak(_contentController.text)} ${_supplyController.text}");
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(0.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('播报内容 (${SpeakTypeEnu.format(widget.speakId)})', style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black87)),
          const SizedBox(height: 8),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(13),
            decoration: BoxDecoration(
              color: Colours.grey,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Text(_contentController.text, style: const TextStyle(fontSize: 14, color: Colors.black87)),
          ),
          const SizedBox(height: 16),
          const Text('补充播报', style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black87)),
          const SizedBox(height: 8),
          TextField(
            controller: _supplyController,
            decoration: const InputDecoration(
              filled: true,
              fillColor: Colours.grey,
              contentPadding: EdgeInsets.all(13),
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
                borderRadius: BorderRadius.all(Radius.circular(5)),
              ),
            ),
            onChanged: (value) => _updatePreview(),
          ),
          const SizedBox(height: 16),
          Text(_previewText, style: const TextStyle(fontSize: 13, color: Colours.blue13345F)),
          const SizedBox(height: 10),

          /// 构建一个3列网格视图，用于显示可选择的按钮项
          ///
          /// 该网格具有以下特性：
          /// - 固定3列布局，元素间有10像素间距
          /// - 禁用滚动功能，网格会根据内容自适应高度
          /// - 每个网格项根据canUse状态显示不同样式
          /// - 点击网格项会触发_toggleItem回调函数
          GridView.builder(
            shrinkWrap: true,
            // 使GridView根据内容自适应高度
            physics: const NeverScrollableScrollPhysics(),
            // 禁用滚动功能
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 120, // 每个item最大宽度100
              mainAxisSpacing: 10, // 垂直间距
              crossAxisSpacing: 10, // 水平间距
              childAspectRatio: 2.5, // 宽高比 = width/height = 100/40 = 2.5
            ),
            itemCount: _btnList.length,
            // 网格项总数
            itemBuilder: (context, index) {
              // 构建每个网格项的回调函数
              final item = _btnList[index]; // 获取当前项数据
              return GestureDetector(
                onTap: () => _toggleItem(item), // 设置点击事件处理
                child: Container(
                  decoration: BoxDecoration(
                    color: item.canUse ? Colours.app_main : Colors.white, // 根据状态设置背景色
                    borderRadius: BorderRadius.circular(5), // 设置圆角
                    border: Border.all(
                      color: item.canUse ? Colours.app_main : Colours.blue13345F, // 根据状态设置边框颜色
                    ),
                  ),
                  alignment: Alignment.center, // 文本居中对齐
                  child: Text(
                    item.payTypeName, // 显示按钮文本
                    style: TextStyle(
                      fontSize: 14,
                      color: item.canUse ? Colors.white : Colours.blue13345F, // 根据状态设置文本颜色
                    ),
                  ),
                ),
              );
            },
          ),

          const SizedBox(height: 24),
          SizedBox(
            width: double.infinity,
            height: 40,
            child: ElevatedButton(
              onPressed: _save,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colours.app_main,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
              child: const Text(
                "保存",
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          const SizedBox(height: 8),
          SizedBox(
            width: double.infinity,
            height: 40,
            child: OutlinedButton(
              onPressed: _preview,
              style: OutlinedButton.styleFrom(
                side: const BorderSide(color: Colours.blue13345F),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
              child: Text(
                "试听",
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Colours.blue13345F,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
